package com.my.sender;

import com.my.util.MailUtil;
import com.my.util.PhoneCode;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RabbitListener(
        bindings = @QueueBinding(
                value = @Queue(value = "${mq.user.config.queue.phone.push}", autoDelete = "true"),
                exchange = @Exchange(value = "${mq.user.config.phone.exchange}", type = ExchangeTypes.FANOUT)
        )
)
public class UserPhoneSender {

    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    /**
     * 接收消息的方法，采用消息队列监听机制
     *
     * @param phone
     */
    @RabbitHandler
    public void process(String phone) {
        PhoneCode.getPhonemsg(phone);
        System.out.println("User-Phone-Sender:"+ MailUtil.getCode());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.opsForValue().set("user" + phone, PhoneCode.getCode(), 5, TimeUnit.MINUTES);
    }
}
